<template>
  <el-table :data="tableData" style="width: 100%" v-loading="loading">
    <el-table-column fixed prop="xxmc" label="学校" width="150" />
    <el-table-column prop="major" label="专业" width="120" />
    <el-table-column prop="index" label="指标" width="120" />
    <el-table-column prop="jsxm" label="教师姓名" width="320" />
    <el-table-column prop="rclx" label="人才类型" width="300" />
    <el-table-column prop="fd" label="分数" width="320" />
  </el-table>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watchEffect } from 'vue'
import { useDataStore } from "@/stores/choose.js"
import { fetchXiangxiData, processTableData } from "@/service/xiangxiservice.js"

const tableData = ref([{
  xxmc: '',
  major: '',
  index: '',
  jsxm: '',
  rclx: '',
  fd: '',
}])

const dataScore = useDataStore()
const loading = ref(false)
const zhibiao = "高层次称号"
const STORAGE_KEY = 'gccchTableDate'

// 加载数据函数
const loadData = async () => {
  loading.value = true
  try {
    const rawData = await fetchXiangxiData(zhibiao, dataScore.selectedData)
    console.log("rawData",rawData)
    const processedData = processRawData(rawData, dataScore.selectedData)
    tableData.value = processTableData(processedData)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(tableData.value))
  } catch (error) {
    console.error("数据加载失败:", error)
  } finally {
    loading.value = false
  }
}

// 处理原始API响应数据
const processRawData = (responses, selectedData) => {
  return responses.map((res, index) => {
    const dataItems = res?.data?.[0]?.data || []

    if (dataItems.length === 0) {
      return {
        xxmc: selectedData[index].xxmc,
        major: selectedData[index].xnzymc,
        index: zhibiao,
        jsxm: '无',
        rclx: '无',
        fd: '0',
      }
    }

    return dataItems.flatMap(item => ({
      xxmc: item.xxmc || item.xwdm || "无该校数据",
      major: item.xnzymc || item.major || '无数据',
      index: zhibiao,
      jsxm: item.jsxm || '无数据',
      rclx: item.rclx || '无数据',
      fd: item.df ?? '无数据',
    }))
  })
}

// 初始化数据
const initData = () => {
  const savedData = localStorage.getItem(STORAGE_KEY)
  if (savedData && savedData !== '[]') {
    tableData.value = JSON.parse(savedData)
    loading.value = false
  } else {
    loadData()
  }
}

// 监听数据变化
watchEffect(() => {
  if (dataScore.selectedOptions) {
    console.log("重新加载数据")
    localStorage.removeItem(STORAGE_KEY)
    loadData()
  }
})

// 生命周期钩子
onMounted(() => {
  initData()
  window.addEventListener('beforeunload', () => {
    localStorage.removeItem(STORAGE_KEY)
  })
})

onBeforeUnmount(() => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tableData.value))
  window.removeEventListener('beforeunload', () => {
    localStorage.removeItem(STORAGE_KEY)
  })
})
</script>

<style></style>
